package SE010;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class showTask
 */
@WebServlet("/showTask")
public class showTask extends HttpServlet{//显示教师或学生在某一班级的所有任务
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        SimpleDateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        Date dateNow = new Date();//获取当前时间
        Date deadline = null;//记录数据库中任务截止日期
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String UserID = request.getParameter("UserID");
        String InviteID = request.getParameter("InviteID");
        String taskID = null;
        String taskTheme = null;
        String taskIssuTime = null;
        String taskDeadline = null;
        float completeRate = 0;
        DecimalFormat df = new DecimalFormat("#0.0%");//任务进度输出格式调整
        String url = "jdbc:mysql://localhost:3306/listsystem";//与本机的3306端口建立连接，进入数据库listsystem
        String driverName = "com.mysql.jdbc.Driver";//驱动注册
        String userName = "root";
        String password = "root";
        String role = null;//标识符，记录身份（教师/学生）
        Connection conn = null;//用于建立与数据库的连接
        Statement staRole = null;
        ResultSet rsRole = null;
        try{
            Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作 
            conn = DriverManager.getConnection(url, userName, password);
        }catch(Exception e){
            System.out.println(e);
        }
        //获取该ID的身份角色信息
        String roleCheckSql = "select Identity from user_t where UserID='"+UserID+"'";
        try {
            if(conn != null) {
                staRole = conn.createStatement();
            }
            if(staRole != null) {
                rsRole = staRole.executeQuery(roleCheckSql);
            }
            if(rsRole != null && rsRole.next()) {
                role = rsRole.getString("Identity");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(rsRole != null)
                    rsRole.close();
                if(staRole != null)
                    staRole.close();
                if(conn != null)
                    conn.close();
                rsRole = null;
                staRole = null;
                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        boolean flag = true;
        String sql = null;
        if(role == null || role.equals("")) {//用户表中无此ID的相关身份信息
            out.print("<html>");
            out.print("<head>");
            out.print("<title>信息出错!</title>");
            out.print("</head>");
            out.print("<body>");
            out.print("<center>");
            out.print("<h2>相关信息有误，请联系管理员进行处理!</h2>");
            out.print("<input type=\"button\" value=\"返回\" onclick=\"window.location.href='showTask10.jsp'\"/>");
            out.print("</center>");
            out.print("</form>");
            out.print("</body>");
            out.print("</html>");
            flag = false;
        } 
        if(flag) {//身份信息出错时，阻止继续执行
            if(role != null && role.equals("学生")) {
                sql = "select TaskID,TaskTheme,TaskIssuTime,TaskDeadline,CompleteRate from v_task_stu where TaskGroup='"+InviteID+"' and StudentID='"+UserID+"'";
            }
            else if(role != null && role.equals("教师")){
                sql = "select TaskID,TaskTheme,TaskIssuTime,TaskDeadline,CompleteRate from v_task_tea where ClassID='"+InviteID+"' and TeacherID='"+UserID+"'";
            }
            Statement sta = null;
            ResultSet rs = null;
            try{
                Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作 
                conn = DriverManager.getConnection(url, userName, password);
            }catch(Exception e){
                System.out.println(e);
            }
            try {
                if(conn != null) {
                    sta = conn.createStatement();
                }
                if(sta != null && sql != null) {
                    rs = sta.executeQuery(sql);
                }
                out.print("<html>");
                out.print("<head>");
                out.print("<title>任务列表</title>");
                out.print("</head>");
                out.print("<body>");
                out.print("<center>");
                int num = 1;
                while(rs != null && rs.next()) {
                    taskID = rs.getString("TaskID");
                    taskTheme = rs.getString("TaskTheme");
                    taskIssuTime = rs.getString("TaskIssuTime");
                    taskDeadline = rs.getString("TaskDeadline");
                    try {
                        deadline = dfDate.parse(taskDeadline);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    completeRate = Float.parseFloat(rs.getString("CompleteRate")); 
                    //不同身份跳转指向不同表单
                    if(role != null && role.equals("学生")) {
                        out.print("<a href=\"showTaskContent?UserID="+URLEncoder.encode(UserID)+"&InviteID="+URLEncoder.encode(InviteID)+"&taskID="+URLEncoder.encode(taskID)+"&num="+num+"\">"+ num++ +"."+taskTheme+"进度:"+df.format(completeRate)+"</a>"+"<br>");
                        //out.print("<a href=\"showTaskContent?UserID="+UserID+"&InviteID="+InviteID+"&taskID="+taskID+"&num="+num+"\">"+ num++ +"."+taskTheme+"进度:"+df.format(completeRate)+"</a>"+"<br>");
                    }
                    else if(role != null && role.equals("教师")){
                        out.print("<a href=\"showTaskStu?UserID="+URLEncoder.encode(UserID)+"&InviteID="+URLEncoder.encode(InviteID)+"&taskID="+URLEncoder.encode(taskID)+"&num="+num+"\">"+ num++ +"."+taskTheme+"进度:"+df.format(completeRate)+"</a>"+"<br>");
                        //out.print("<a href=\"showTaskStu?UserID="+UserID+"&InviteID="+InviteID+"&taskID="+taskID+"&num="+num+"\">"+ num++ +"."+taskTheme+"进度:"+df.format(completeRate)+"</a>"+"<br>");
                    }
                    if(deadline.getTime()>dateNow.getTime()) {//截止日期大于当前日期，任务未截止
                        out.print("开始时间:"+taskIssuTime+"截止时间:"+taskDeadline+"状态:进行中"+"<br>");
                    }
                    else if(deadline.getTime()<dateNow.getTime()) {//截止日期小于当前日期，任务截止
                        out.print("开始时间:"+taskIssuTime+"截止时间:"+taskDeadline+"状态:已截止"+"<br>");
                    }
                }
                if(role != null && role.equals("教师")){
                    out.print("<input type=\"button\" value=\"按学生查看\" onclick=\"window.location.href='showStu?UserID="+URLEncoder.encode(UserID)+"&InviteID="+URLEncoder.encode(InviteID)+"'\"/>");
                    //out.print("<input type=\"button\" value=\"按学生查看\" onclick=\"window.location.href='showStu?UserID="+UserID+"&InviteID="+InviteID+"'\"/>");
                }
                out.print("<input type=\"button\" value=\"返回\" onclick=\"window.location.href='showTask10.jsp'\"/>");
                out.print("</center>");
                out.print("</form>");
                out.print("</body>");
                out.print("</html>");
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(rs != null)
                        rs.close();
                    if(sta != null)
                        sta.close();
                    if(conn != null)
                        conn.close();
                    rs = null;
                    sta = null;
                    conn = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
